<template>
  <div class="form-page">
    <Card :bordered="false" :dis-hover="true">
      <p slot="title" style="color: #666">
        <span
          class="iconfont icon-changyongtubiao-xianxingdaochu-zhuanqu-"
          style="font-size: 20px"
        ></span>
        添加版本
      </p>
      <p slot="extra" style="color: #999; font-size: 12px">
        <label style="color: #ff3b30">*</label> 为必填
      </p>
      <Form
        ref="formValidate"
        :model="bloc.model"
        :rules="ruleValidate"
        :label-width="100"
      >
        <FormItem label="版本号：" prop="versionName" required>
          <Input
            v-model="bloc.model.versionName"
            style="width: 400px"
            placeholder="请注意输入格式:如(0.0.1)"
          />
        </FormItem>
        <FormItem label="版本编码：" prop="versionCode" required>
          <Input v-model="bloc.model.versionCode" style="width: 400px" />
        </FormItem>
        <FormItem label="更新类型：" prop="upgradeType" required>
          <RadioGroup v-model="bloc.model.upgradeType">
            <Radio label="PAD">IPAD</Radio>
            <Radio label="VR">VR</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="更改状态：" prop="updateStatus" required>
          <RadioGroup v-model="bloc.model.updateStatus">
            <Radio label=1>不强制更新</Radio>
            <Radio label=2>强制更新</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="APK文件：" prop="downloadUrl" required>
          <Upload
            :show-upload-list="false"
            :action="uploadAction"
            :max-size="512000"
            :format="['apk']"
            :headers="uploadHeaders"
            :on-format-error="handleFormatError1"
            :on-exceeded-size="handleMaxSize1"
            :on-progress="handleProgress"
            :on-success="handleSuccessFile"
            :on-error="handleError"
          >
            <Button icon="ios-filing" :disabled="elProgress">选择附件</Button>
          </Upload>
          <a v-if="bloc.model.extName" :href="bloc.model.url">{{
            bloc.model.extName
          }}</a>
          <p style="margin-left: 15px" v-if="!elProgress">支持 apk 格式</p>
          <p style="margin-left: 15px" v-if="elProgress">正在上传请等待...</p>
        </FormItem>
        <FormItem label="更改内容：" prop="modifyContent" required>
          <Input
            style="width: 400px"
            type="textarea"
            v-model="bloc.model.modifyContent"
            :rows="5"
            maxlength="50"
            show-word-limit
          ></Input>
        </FormItem>
        <FormItem label="设备型号" prop="modelName" required>
          <Input
            style="width: 400px"
            disabled
            v-model="bloc.model.modelName"
          ></Input>
        </FormItem>
      </Form>
      <div style="margin: 20px 0px 35px 25px">
        <Button style="width: 100px; height: 40px" @click="handleCancel">返回</Button>
        <Button
          style="margin-left: 30px; width: 100px; height: 40px"
          type="primary"
          :loading="btnload.loading"
          @click="handleSubmit('formValidate')"
          >保存
        </Button>
      </div>
    </Card>
  </div>
</template>
<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import { VersionBloc } from '@/view/device/Edit/version/VersionBloc';
import { store } from '@/store/Store';
import { baseUrl } from '@/base/Request';
import { Loading } from '@/base/Loading';
import { router } from '@/config/Router';
import { Route } from 'vue-router';

@Component({
  components: {}
})
export default class extends Vue {
  beforeRouteEnter(to: Route, from: Route, next: (vm: any) => void) {
    next((vm) => {
      vm.bloc
        .getModel(vm.idx)
        .catch((e) => {
          vm.$Message.error('操作错误');
        });
      vm.bloc.model.modelId = vm.idx
    });
  }
  @Prop({ type: Number })
  readonly init!: number;
  bloc = new VersionBloc();
  btnload = new Loading();
  snList: any = {
    1: 'GY',
    2: 'SQ',
    3: 'SY',
    4: 'ZW',
    5: 'WZ',
    6: 'ORDER'
  };
  formValidate: any = {
    type: '',
    switch: true
  };
  validateVersions = (rule, value, callback) => {
    if (value === undefined) {
      callback(new Error('版本号不能为空'));
    } else {
      let reg2 = /^(\d+)\.(\d+)\.(\d+)$/;
      if (!reg2.test(value)) {
        callback(new Error('请输入正确的版本号如:0.0.1'));
      }
      callback();
    }
  };
    validateCode = (rule, value, callback) => {
        if (value === undefined) {
            callback(new Error('版本编码不能为空'));
        } else {
            let reg2 = /^[0-9]+$/;
            if (!reg2.test(value)) {
                callback(new Error('版本编码仅可输入纯数字'));
            }
            callback();
        }
    };
  ruleValidate: any = {
    modifyContent: [
      { required: true, message: '更改内容不能为空', trigger: 'blur' }
    ],
    versionCode: [
        { validator: this.validateCode, trigger: 'blur' }
    ],
    versionName: [{ validator: this.validateVersions, trigger: 'blur' }],
    upgradeType: [
      { required: true, message: '更新类型不能为空', trigger: 'blur' }
    ],
    downloadUrl: [
      { required: true, message: 'APK文件不能为空', trigger: 'blur' }
    ],
    modelName: [
      { required: true, message: '设备型号不能为空', trigger: 'blur' }
    ],
      updateStatus: [
          { required: true, message: '状态不能为空', trigger: 'blur' }
      ]
  };
  $refs!: {
    formValidate: HTMLFormElement;
  };
  enable = true;
  elProgress=false;
  get uploadHeaders() {
    return {
      Authorization: 'Bearer ' + store.state.auth.accessToken
    };
  }

  get uploadAction() {
    return `${baseUrl}/api/upload/apk`;
  }

  get idx() {
    return Number(this.$route.params.id);
  }

  handleMaxSize1(file) {
    this.$Message.error('文件大小不能超过200M')
  }
  handleFormatError1(file) {
    this.$Message.error('请选择格式为.apk格式的文件');
  }
    handleProgress() {
        this.elProgress = true;
    }
    handleError() {
        this.elProgress = false;
        this.$Message.error('上传失败');
    }
  handleSuccessFile(res, file) {
    this.elProgress = false;
    this.bloc.model.downloadUrl = res.data.url;
    this.bloc.model.apkSize = res.data.size;
    this.bloc.model.extName = res.data.extName;
  }

  handleCancel() {
    this.$router.push({
      path: '/device/nav/version/' + this.idx,
      query: {sortId: this.$route.query.sortId}
    });
  }

  handleSubmit(name) {
    this.$refs[name].validate((valid) => {
      if (valid) {
        this.btnload.loading = true;
        this.bloc
          .addApkVersion(
            this.bloc.model.downloadUrl,
            this.bloc.model.apkSize,
            this.bloc.model.modifyContent,
            this.bloc.model.upgradeType,
            this.bloc.model.versionCode,
            this.bloc.model.versionName,
            this.bloc.model.modelId,
            this.bloc.model.updateStatus,
            this.bloc.model.detailedContent
          )
          .then((res) => {
            this.$Message.success('添加版本成功');
            this.btnload.loading = false;
            this.handleCancel();
          })
          .catch((err) => {
              this.btnload.loading = false;
              if (err.name === 'version_code_error') {
                  this.$Message.error('添加版本失败,' + err.message);
              } else {
                  this.$Message.error('添加版本失败');
              }
          });
      }
    });
  }

  mounted() {}
}
</script>
<style lang="less" scoped>
.top {
  height: 50px;
  width: 100%;
  border-bottom: 1px solid rgba(204, 204, 204, 1);
  font-size: 18px;
  line-height: 50px;
}

/deep/ .ivu-form-item-content {
  display: flex !important;
  justify-content: start !important;
  align-items: center !important;
}
</style>
